<?php

namespace App\HttpController;
use EasySwoole\EasySwoole\Config;
use EasySwoole\Mysqli\QueryBuilder;
use EasySwoole\Http\AbstractInterface\Controller;
use App\Models\AdminModel;
use App\Models\UserModel;
use EasySwoole\Component\Di;
use App\HttpController\UserBase;
use App\Models\Project;
use App\Models\Level;
use App\Models\Assign;
use App\Models\File;
use App\Models\History;

use App\Models\Industry;
use App\Models\Apptype;

class Index extends UserBase
{

    function additem(){
        $itemid = $this->input('id');
        $isupdate = $this->input('isupdate');

        $who = $this->who;
        $params =  $this->request()->getRequestParam();
        $params['addedby'] = $who['id'];
        $params['addTime'] = time();

        $params['lxtime'] = strtotime($params['lxtime']);



        try {
            // 开启事务
            \EasySwoole\ORM\DbManager::getInstance()->startTransaction();
var_dump($isupdate);
            if($isupdate == 'true'){
                $params['status'] = 0;

                var_dump("true.......");
                $model = Project::create($params);
                $res = $model->update($params,['id'=>$itemid]);


            }else{


                unset($params['id']);
                $model = Project::create($params);
                $res = $model->save();


            }
           
            if ($res>0)  {

                $files = $params['files'];
                $file2 = $params['file2'];
                $datafiles = [];

                foreach($files as $k=>$v){

                    array_push($datafiles,[
                        "filename"=>$v['filename'],
                        "path"=>$v['filepath'],
                        "itemid"=>$res,
                        "addedby"=>$this->who['id'],
                        "addtime"=>time()

                    ]);

                }

                foreach($file2 as $k=>$v){

                    array_push($datafiles,[
                        "filename"=>$v['filename'],
                        "path"=>$v['filepath'],
                        "itemid"=>$res,
                        "addedby"=>$this->who['id'],
                        "addtime"=>time(),
                        'ischoose'=>1

                    ]);

                }


                var_dump($datafiles);

                File::create()->saveall($datafiles,true,false);


            }

            \EasySwoole\ORM\DbManager::getInstance()->commit();
    
            $this->writeJson(200,['code'=>200],"ok");
        } catch(\Throwable  $e){
            // 回滚事务
            \EasySwoole\ORM\DbManager::getInstance()->rollback();
            var_dump($e->getMessage());
            $this->writeJson(404,"error");
        }
    }

    function generate_password( $length = 8 ) {
         // 密码字符集，可任意添加你需要的字符
         $chars = 'abcdefghijklmnopqrstuvxyz1234567890';

         $password = '';
         for ( $i = 0; $i < $length; $i++ ) 
         {
          $password .= $chars[ mt_rand(0, strlen($chars) - 1) ];
         }

         return $password;
}



function generatenumber() {
    // 密码字符集，可任意添加你需要的字符
    $chars = 'abcdefghijklmnopqrstuvxyz1234567890';

    $password = '';
    for ( $i = 0; $i < 4; $i++ ) 
    {
     $password .= $chars[ mt_rand(0, strlen($chars) - 1) ];
    }
    $code = sprintf("%s%s",date('Y').date('m').date('d'),$password);
    $this->writeJson(200,['code'=>200,'number'=>$code]);
}







    function upload()
    {
        $request = $this->request();
        $files = $request->getUploadedFiles();
        if(empty($files)){
            $this->writeJson(500,"no files found");
            return false;
        }
  
        $arr = [];
        foreach($files as $file){
                $filename = $file->getClientFilename();
                $path = '/uploadfiles/'.md5(time()).substr(0,4).".".explode('.',$filename)[1];
                $flag = $file->moveTo($path);
                $arr[explode('.',$filename)[0]] = $path;
        }
        

            $this->writeJson(200,$arr);
        }

    function list(){
        //+"&lxnumber="+lxnumber+
      //  "&name="+name+"&wtdw="+wtdw+"&bzjg="+bzjg+"&addtime="+addtime
        $limit = \EasySwoole\EasySwoole\Config::getInstance()->getConf('pagelimit');
        $page = $this->input('page',1);
        $owner = $this->input("owner","");
        $lxnumber = $this->input("lxnumber","");
        $name = $this->input("name","");
        $wtdw = $this->input("wtdw","");
        $bzjg = $this->input("bzjg","");
        $addtime = $this->input("addtime","");

        $industry = $this->input("industry","");

        $where = [];
       $model =  Project::create()->where(['addedby'=>$this->who['id']]);
        if($owner == 'null'){
            $owner = "";
        }

        if($industry == 'null' || $industry == "1"){
            $industry = "";
        }

        if($lxnumber == 'null'){
            $lxnumber = "";
        }
        if($name == 'null'){
            $name = "";
        }
        if($wtdw == 'null'){
            $wtdw = "";
        }
        if($bzjg == 'null'){
            $bzjg = "";
        }
        if($addtime == 'null'){
            $addtime = "";
        }else{
            $addtime = strtotime($addtime);
        }


        if($owner){
            $model = $model->where("owner","%".$owner."%",'like');
        }

        if($lxnumber){
            $model = $model->where("lxnumber","%".$lxnumber."%",'like');
        }
        if($name){
            var_dump($name);
            $model = $model->where("name","%".$name."%",'like');
        }
        if($wtdw){
            $model = $model->where("wtdw","%".$wtdw."%",'like');
        }
        if($bzjg){
            $model = $model->where("bzjg","%".$bzjg."%",'like');
        }
        if($addtime){

            $model = $model->where(["addTime"=>$addtime]);
        }

        if($industry){
            $model = $model->where("industry","%".$industry."%",'like');
        }


        
        $model = $model->order('id', 'DESC')->limit($limit * ($page - 1), $limit)->withTotalCount();
        $list = $model->all(null);
        $result = $model->lastQueryResult();
        $total = $result->getTotalCount();
        $pagecon = $this->showPageStringAsAJAXForitem("jumpage",$page,$limit,$total,$owner);
        $this->writeJson(200,['list'=>$list,'pg'=>$pagecon]);
    }

    function getdetail(){
        $params = $this->request()->getRequestParam();
        $id = $params['id'];
        if (!$id) {
            $this->writeJson(404,"NOT FOUND ITEM");
        }
        $project = Project::create()->get(["id"=>intval($id)]);
        $files = File::create()->where(['itemid'=>$id])->all();
        $project['lxtime'] =date("Y-m-d",$project['lxtime']);
        $logs = History::create()->join('user_list','user_list.id = approve_history.userid')->all(['itemid'=>intval($id)]);
        $this->writeJson(200,['item'=>$project,'logs'=>$logs,'files'=>$files]);
    }


    function getlevels(){
       $levels =  Level::create()->all(['status'=>1]);
       $industry = Industry::create()->all(['status'=>1]);
       $type = Apptype::create()->all(['status'=>1]);
       $this->writeJson(200,['level'=>$levels,'industry'=>$industry,'type'=>$type]);
    }



    function getowners(){

        $yzs = UserModel::create()->where(['status'=>1,'type'=>2])->column('userAccount');
        $this->writeJson(200,$yzs);


    }
   
}
